<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RegisterVerify;
use App\Validate\SendNoteCodeValidate;


/**
 * 发送短信验证码
 */
class SendNoteCodeController extends Controller
{
    public $validate = null;
    public $model = null;
    public $noteObj = null;
    public function __construct()
    {
        $this->validate = new SendNoteCodeValidate();
        $this->model = new RegisterVerify();
        $this->noteObj = new SendNoteTemplateController();
    }


    /**
     * 发送验证码
     * @param tel     电话号码
     * @param key     电话号码+tel_key    后的MD5值     md5(13030303030.tel_key)
     * @param state   类型  1、在线办证     2、在线注册（绑定手机号码）
     */
    public function sendVerify(Request $request)
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('send')->check($request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->where('phone', $request->tel)->orderByDesc('id')->first();
        if ($res && $res['create_time'] > date('Y-m-d H:i:s', strtotime('-1 min'))) {
            return $this->returnApi(202, '验证码已发送，请勿重复获取！');
        }

        $number = get_rnd_number(6); //获取验证码
        //选择模板编号
        $tel = $request->tel;
        $state = strtoupper($request->state);
        $template =  $this->model->getTemplate($state);
        $signature =  $template['sign'];
        $template_id =  $template['template_id'];
        $result = $this->noteObj->sendTemplateVerify($tel, $number, $signature, $template_id); //手机号码，替换内容数组，模板ID
        if ($result === true) {
            $expir = strtotime("+5 minutes"); //默认是5分钟，和模版对应，模版是固定配置时间
            $expir_time = date('Y-m-d H:i:s', $expir);
            //发送成功之后，先删除之前此电话号码的验证码 + 储蓄验证码
            $this->model->addVerify($tel, $number, $expir_time);

            return $this->returnApi(200, '发送成功', true);
        } else {
            $msg = $result ? $result : '验证码发送失败';
            return $this->returnApi(202, $msg);
        }
    }
}
